package cn.com.yd.commons.grpc.config;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;

/**
 * grpc channel工厂
 * 
 * @author 张蕴
 *
 */

public class ChannelFactory extends BasePooledObjectFactory<ManagedChannel> {
	private ManagedChannelBuilder managedChannelBuilder;

	public ChannelFactory(ManagedChannelBuilder managedChannelBuilder) {
		this.managedChannelBuilder = managedChannelBuilder;
	}

	@Override
	public ManagedChannel create() throws Exception {
		return managedChannelBuilder.build();
	}

	@Override
	public PooledObject<ManagedChannel> wrap(ManagedChannel obj) {
		return new DefaultPooledObject<>(obj);
	}

	@Override
	public boolean validateObject(final PooledObject<ManagedChannel> p) {
		if (p.getObject() == null || p.getObject().isShutdown() || p.getObject().isTerminated()) {
			return false;
		}
		return true;
	}
}
